﻿using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using BEGDC.PreContract.BLL;
using BEGDC.PreContract.BLL.Authentication;
using BEGDC.Utility.Castle;
using PreContractInfo = BEGDC.PreContract.DAL.PreContractInfo;

namespace PreContractWeb.Task
{
    public partial class AllPre_Contracts : Page
    {
        private string DataFilter
        {
            get
            {
                if (ViewState["DataFilter"] == null)
                {
                    return string.Empty;
                }
                else
                {
                    return (string)ViewState["DataFilter"];
                }
            }
            set
            {
                ViewState["DataFilter"] = value;
            }
        }

        private SortManager SortManager
        {
            get
            {
                if (ViewState["SortManager"] == null)
                {
                    return new SortManager();
                }
                else
                {
                    return (SortManager)ViewState["SortManager"];
                }
            }
            set
            {
                ViewState["SortManager"] = value;
            }
        }

        protected string SearchSQL
        {
            get
            {
                if (Session["SearchSQL"] == null)
                {
                    string guid = Page.Request.QueryString["guid"];
                    if (guid != null)
                    {
                        if (Session[guid] == null)
                            return string.Empty;
                        return Session[guid] as string;
                    }
                    return string.Empty;
                }
                else
                {
                    string guid = Page.Request.QueryString["guid"];
                    if (guid != null)
                    {
                        Session[guid] = Session["SearchSQL"];
                        Session["SearchSQL"] = null;

                        return Session[guid] as string;
                    }
                    return Session["SearchSQL"] as string;
                }
            }
            set
            {
                Session["SearchSQL"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.Request.QueryString["Download"] != null)
            {
                btnExport_Click(null, null);
                return;
            }


            #region  Response Write
            Response.Write(@"

                            <style>
                            .table_ajax
                            {
	                            border-top: 1px;
	                            border-top-color:#636363;
	                            border-top-style:solid;
	                            border-bottom: 1px;
	                            border-bottom-color:#636363;
	                            border-bottom-style:solid;
	                            border-left: 1px;
	                            border-left-color:#636363;
	                            border-left-style:solid;
	                            border-right: 1px;
	                            border-right-color:#636363;
	                            border-right-style:solid;
	                            font-family:Arial, Helvetica, sans-serif;
	                            font-size:12px;
	                            color: #636363;
	                            height: 20px;
                            	
                            }
                            </style>
                            <div style=""position: absolute; left: 40%; top: 40%; overflow: hidden; background-color: white;
                            filter: alpha(opacity=50); opacity: 0.5; -moz-opacity: 0.5;"" id=""AJAXProgress"">
                            <table class=""table_ajax"">
                                <tr>
                                    <td style=""width: 35px"">
                                        <img src=""../Images/roller.gif"" /></td>
                                    <td style=""width: 100px"">
                                        Processing...</td>
                                </tr>
                            </table>
                        </div>");
            #endregion

            Page.Header.Controls.Add(new LiteralControl(@"<base target=""_self"" />"));

            if (!Page.IsPostBack)
            {
                Response.Flush();

                btnAddNew.Visible = false;
                btnSendEmail.Visible = false;
                btnDelete.Visible = false;

                this.CreateGridColumn();

                if (Page.User.IsInRole(Role.EnumRole.Admin.ToString()))
                {
                    btnAddNew.Visible = true;
                    btnSendEmail.Visible = true;
                    btnDelete.Visible = true;
                }
                else
                {
                    gvMain.Columns[2].Visible = false;
                }

                if (Page.Request.QueryString["Search"] != null)
                {
                    btnAddNew.Visible = false;
                    if (Page.Request.QueryString["Search"] == "2")
                    {
                        btnAddNew.Visible = false;
                    }
                }

                BaseFunction.BindContractStatusDropDownList(ddlContractStatus, string.Empty, true);
                ddlContractStatus.Items.RemoveAt(3);

                BindGridView(true);
            }

            if (returnvalue != null && returnvalue.Value != "")
            {
                returnvalue.Value = "";
                BindGridView(false);
                if (gvMain.PageCount >= pgMain.GVCurrentPageIndex)
                {
                    pgMain.PageChangeEvent();
                }
            }
        }

        public void BindGridView(bool removeCFI)
        {
            try
            {
                string strpermission = ((PCPrincipal)Page.User).DataPermission;

                IPreContractInfo contractservice = (IPreContractInfo)AppContainer.Instance[Services.CONST_PreContractInfo_Service];

                if (Page.Request.QueryString["Search"] != null) //查询页面跳转过来的.
                {
                    tdStatus.Visible = false;
                    tdStatusText.Visible = false;
                    if (Page.Request.QueryString["Search"] == "1")
                    {
                        if (strpermission != string.Empty)
                        {
                            if (SearchSQL.Trim() != string.Empty)
                                strpermission += " AND " + SearchSQL;
                        }
                        else
                            strpermission = SearchSQL;
                    }
                    else
                    {
                        strpermission = SearchSQL;
                    }
                    //Joan 2008-11-05 to trim last "AND"
                    if (strpermission.Length > 0)
                    {
                        if (strpermission.Substring(strpermission.Length - 3, 3) == "AND")
                            strpermission = strpermission.Substring(0, strpermission.Length - 3);
                    }
                }
                else
                {
                    if (strpermission != string.Empty)
                        strpermission += string.Format(" AND ({0} = {1} Or {2} = {3} ) ", PreContractInfo.CONST_StatusID, Convert.ToString((int)DicItem.PreContractStatus.Pending), PreContractInfo.CONST_StatusID, Convert.ToString((int)DicItem.PreContractStatus.PartWon));
                    else
                        strpermission += string.Format(" ({0} = {1} Or {2} = {3} ) ", PreContractInfo.CONST_StatusID, Convert.ToString((int)DicItem.PreContractStatus.Pending), PreContractInfo.CONST_StatusID, Convert.ToString((int)DicItem.PreContractStatus.PartWon));
                }

                DataTable dt = contractservice.GetPreContractInfo(strpermission);
                dt.DefaultView.Sort = SortManager.ToString();
                dt.DefaultView.RowFilter = DataFilter;

                //filter yuliang 2010-5-26
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (int.Parse(dt.Rows[i]["DelayWeeks"].ToString()) < 0)
                        dt.Rows[i]["DelayWeeks"] = 0;
                }

                gvMain.DataSource = dt.DefaultView;
                gvMain.DataBind();

                //yuliang 2010-5-26
                //if (removeCFI)
                //{
                //    int EemployeeId = ((BEGDC.PreContract.BLL.Authentication.PCIdentity)Page.User.Identity).EmployeeId;
                //    BEGDC.PreContract.BLL.IUserRole iUserRole = (BEGDC.PreContract.BLL.IUserRole)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_UserRole_Service];
                //    DataTable dtEmpRole = iUserRole.GetUserRole_DataTable(String.Format("EmployeeID = {0}", EemployeeId));
                //    BEGDC.PreContract.DAL.Role role = new BEGDC.PreContract.DAL.Role();
                //    BEGDC.PreContract.BLL.IRole iRole = (BEGDC.PreContract.BLL.IRole)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Role_Service];

                //    bool isCFIRole = false;
                //    for (int t = 0; t < dtEmpRole.Rows.Count; t++)
                //    {
                //        role = iRole.GetRole(Convert.ToInt32(dtEmpRole.Rows[t]["RoleID"].ToString()));
                //        if (role.Description.Contains("CFI"))
                //        {
                //            isCFIRole = true;
                //            break;
                //        }
                //    }
                //    remove CFI column
                //    if (isCFIRole == false)
                //    {
                //        gvMain.Columns.RemoveAt(24);  
                //    }
                //}

                totalSpan.InnerText = dt.DefaultView.Count.ToString();

                this.pgMain.Visible = true;
                this.pgMain.BindtoGridView(this.gvMain, dt.DefaultView);
                if (this.gvMain.Rows.Count == 0)
                {
                    this.pgMain.Visible = false;
                }
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
            }
        }

        protected void gvMain_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex >= 0)
            {
                e.Row.Cells[3].Text = "<a onclick=\"javascript:ShowPage('" + e.Row.Cells[0].Text.Trim() + "');\">" + e.Row.Cells[1].Text.Trim() + "</a>";
                e.Row.Cells[0].ID = "PreContractID";
                e.Row.Cells[1].ID = "PreContractNo";
            }

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView drv = ((DataRowView)e.Row.DataItem);
                if (Convert.ToInt32(drv.Row[PreContractInfo.CONST_StatusID]) == (int)DicItem.PreContractStatus.Won)
                {
                    e.Row.CssClass = "table_row_3";
                }
                e.Row.Cells[e.Row.Cells.Count - 1].Text = e.Row.Cells[e.Row.Cells.Count - 1].Text.Replace("/", "-");
                //e.Row.Cells[26].Text = e.Row.Cells[26].Text.Replace("1", "正常终审-").Replace("2", "PCAT承诺ValueLine-").Replace("3", "转正时间长或不确定-").Replace("4", "PSO/CAT邮件承诺ValueLine-").Replace("|||", "").TrimEnd(Convert.ToChar("-"));
                if (!string.IsNullOrEmpty(this.lblSpecialApprove.Text))
                {
                    int index = Convert.ToInt32(this.lblSpecialApprove.Text);
                    if (index >= 4)
                    {
                        e.Row.Cells[index].Text = e.Row.Cells[index].Text.Replace("1", "正常终审-").Replace("2", "PCAT承诺ValueLine-").Replace("3", "转正时间长或不确定-").Replace("4", "PSO/CAT邮件承诺ValueLine-").Replace("|||", "").TrimEnd(Convert.ToChar("-"));
                    }
                }
            }
        }

        protected void gvMain_Sorting(object sender, GridViewSortEventArgs e)
        {
            this.pgMain.GVCurrentPageIndex = 1;
            SortManager sort = SortManager;
            sort.DoSort(e.SortExpression);
            SortManager = sort;
            BindGridView(false);
        }

        protected void ddlContractStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.pgMain.GVCurrentPageIndex = 1;
            if (ddlContractStatus.SelectedValue == "")
            {
                DataFilter = string.Empty;
            }
            else
            {
                DataFilter = string.Format("StatusID ='{0}'", ddlContractStatus.SelectedValue);
            }
            BindGridView(false);
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            return;
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < gvMain.Rows.Count; i++)
            {
                CheckBox ck = gvMain.Rows[i].FindControl("chkSelect") as CheckBox;

                if (ck.Checked)
                {
                    string precontractId = gvMain.Rows[i].Cells[0].Text;
                    PreContractInfo precontract = new PreContractInfo();
                    precontract.PreContractID = Convert.ToInt32(precontractId);
                    precontract.Delete();
                }
            }
            this.pgMain.GVCurrentPageIndex = 1;
            BindGridView(false);
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            gvMain.AllowSorting = false;
            //yuliang 2010-5-26

            //int EemployeeId = ((BEGDC.PreContract.BLL.Authentication.PCIdentity)Page.User.Identity).EmployeeId;
            //BEGDC.PreContract.BLL.IUserRole iUserRole = (BEGDC.PreContract.BLL.IUserRole)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_UserRole_Service];
            //DataTable dtEmpRole = iUserRole.GetUserRole_DataTable(String.Format("EmployeeID = {0}", EemployeeId));
            //BEGDC.PreContract.DAL.Role role = new BEGDC.PreContract.DAL.Role();
            //BEGDC.PreContract.BLL.IRole iRole = (BEGDC.PreContract.BLL.IRole)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Role_Service];

            //bool isCFIRole = false;
            //for (int t = 0; t < dtEmpRole.Rows.Count; t++)
            //{
            //    role = iRole.GetRole(Convert.ToInt32(dtEmpRole.Rows[t]["RoleID"].ToString()));
            //    if (role.Description.Contains("CFI"))
            //    {
            //        isCFIRole = true;
            //        break;
            //    }
            //}
            //if (isCFIRole == true)
            //{
            //    gvMain.Columns.RemoveAt(30); //删除发货状态的隐藏列
            //}
            //else
            //{
            //    gvMain.Columns.RemoveAt(29);
            //}

            if (this.IsCFIRole() == false && !string.IsNullOrEmpty(this.lblDeliveredIndex.Text))
            {
                int index = Convert.ToInt32(this.lblDeliveredIndex.Text);
                if (index >= 4)
                {
                    gvMain.Columns.RemoveAt(index);
                }
            }

            this.gvMain.PageSize = Convert.ToInt32(this.totalSpan.InnerText);
            BindGridView(false);
            DataView dt = (DataView)gvMain.DataSource;
            if (dt.Count >= 1)
            {
                BaseFunction.ExportToExcel(Page, gvMain, "Pre-ContractList.xls");
            }
            else
            {
                ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('没有查询结果导出！\nNo data to be exported');</script>");
            }
        }

        private bool IsCFIRole()
        {
            int EemployeeId = ((BEGDC.PreContract.BLL.Authentication.PCIdentity)Page.User.Identity).EmployeeId;
            BEGDC.PreContract.BLL.IUserRole iUserRole = (BEGDC.PreContract.BLL.IUserRole)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_UserRole_Service];
            DataTable dtEmpRole = iUserRole.GetUserRole_DataTable(String.Format("EmployeeID = {0}", EemployeeId));
            BEGDC.PreContract.DAL.Role role = new BEGDC.PreContract.DAL.Role();
            BEGDC.PreContract.BLL.IRole iRole = (BEGDC.PreContract.BLL.IRole)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_Role_Service];

            bool isCFIRole = false;
            for (int t = 0; t < dtEmpRole.Rows.Count; t++)
            {
                role = iRole.GetRole(Convert.ToInt32(dtEmpRole.Rows[t]["RoleID"].ToString()));
                if (role.Description.Contains("CFI"))
                {
                    isCFIRole = true;
                    break;
                }
            }
            return isCFIRole;
        }

        /// <summary>
        /// Create GridView Columns
        /// </summary>
        private void CreateGridColumn()
        {
            string filter = string.Format("DicTypeID = {0} and IsEnabled = 1", BaseFunction.CONST_PRECONTRACT_COLUMNS_DICTYPE);
            IDicItem iDicItem = (IDicItem)AppContainer.Instance[Services.CONST_DicItem_Service];
            DataTable dt = iDicItem.GetDicItem_DataTable(filter);

            int index = 0;
            bool isCFIRole = this.IsCFIRole();

            foreach (DataRow row in dt.Rows)
            {
                BoundField newCol = new BoundField();
                newCol.HeaderText = row["DicItemDesc"].ToString().Replace("-", @"<br/>");
                newCol.DataField = row["DicItemValue"].ToString();
                newCol.SortExpression = row["DicItemValue"].ToString();
                newCol.HtmlEncode = false;
                newCol.ItemStyle.HorizontalAlign = HorizontalAlign.Center;

                if (isCFIRole == false && newCol.DataField == PreContracColumn.CFIPrice)
                    continue;

                if (newCol.DataField == PreContracColumn.SignActual
                    || newCol.DataField == PreContracColumn.PromisedDate
                    || newCol.DataField == PreContracColumn.SignDue
                    || newCol.DataField == PreContracColumn.ERPReceived
                    || newCol.DataField == PreContracColumn.DeliveryDate
                    || newCol.DataField == PreContracColumn.AOGDate
                    || newCol.DataField == PreContracColumn.BlackDate
                    || newCol.DataField == PreContracColumn.CommentPromisedDate)
                {
                    newCol.DataFormatString = "{0:yyyy-MM-dd}";
                }

                if (newCol.DataField == PreContracColumn.SparePrice
                     || newCol.DataField == PreContracColumn.OrionPrice
                     || newCol.DataField == PreContracColumn.CEWPromised
                     || newCol.DataField == PreContracColumn.SalePrice
                     || newCol.DataField == PreContracColumn.CFIPrice
                     || newCol.DataField == PreContracColumn.DeliveryPercent)
                {
                    newCol.DataFormatString = "{0:N2}";
                }

                if (newCol.DataField == PreContracColumn.CEWME
                    || newCol.DataField == PreContracColumn.OrionME
                    || newCol.DataField == PreContracColumn.GAP)
                {
                    newCol.DataFormatString = "{0:N4}";
                }

                if (newCol.DataField == PreContracColumn.Delivered)
                {
                    this.lblDeliveredIndex.Text = (index + 4).ToString();
                }

                if (newCol.DataField == PreContracColumn.SpecialApprove)
                {
                    this.lblSpecialApprove.Text = (index + 4).ToString();
                }

                this.gvMain.Columns.Add(newCol);
                index++;
            }
        }
    }
}
